package classloader;

import java.io.*;

public class MyClassLoader extends ClassLoader {

    private String baseDir;

    public MyClassLoader(String baseDir) {
        this.baseDir = baseDir;
    }

    public MyClassLoader() {
        this(null);
    }

    @Override
    public Class findClass(String name) throws ClassNotFoundException  {
        byte[] b = loadClassFromFile(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassFromFile(String fileName)  {
        String filePath = fileName.replace('.', File.separatorChar) + ".class";
        System.out.println(filePath);

        InputStream inputStream;

        if (baseDir != null) {
            filePath = baseDir + File.separatorChar + filePath;
            try {
                inputStream = new FileInputStream(filePath);
            } catch(Exception exception) {
                exception.printStackTrace();
                inputStream = null;
            }
        } else {
            inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
        }
        System.out.println(filePath);

        // InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
        byte[] buffer;
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int nextValue = 0;
        try {
            while ( (nextValue = inputStream.read()) != -1 ) {
                byteStream.write(nextValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        buffer = byteStream.toByteArray();
        return buffer;
    }
}
